package com.ultrapower.ultracsa.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.support.SessionStatus;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ultrapower.ultracsa.product.dao.UserDao;
import com.ultrapower.ultracsa.product.pojo.User;
import com.ultrapower.ultracsa.product.service.UserService;
import com.ultrapower.ultracsa.product.util.security.SecurityService;

@Service("userService")  
public class UserServiceInfImpl implements UserService{

	@Resource  
    private UserDao userDao;  
	    @Override  
	    public User getUserById(Integer userId) {  
	        return this.userDao.findById(userId);  
	    }
		@Override
		public List<User> getListByAge(Integer age) {
			/*开始分页，参数为页号和页长*/
			PageHelper.startPage(2, 5);
			List<User> userList = this.userDao.getListByAge(age);
			PageInfo page = new PageInfo(userList);
			Long pageTotal = page.getTotal();
			for(User u:userList){
	        	System.out.println(u.getUserName());
	        }
			return userList;
		}
		/** 
	     * 事务处理必须抛出异常，Spring才会帮助事务回滚 
	     * @param users 
	     */  
	    @Transactional  
	    @Override  
		public void insertUser(User user) {
	    	if("root".equals(user.getUserName())){
	    		this.userDao.insertUser(user);
	    	}else{
	    		throw new RuntimeException();
	    	}
		}
		@Override
		public String login(User user,SessionStatus sessionStatus,HttpSession httpSession) {
			if(userDao.findUser(user)==null){
				sessionStatus.setComplete();
				return "redirect:/loginError";
			}else{
				httpSession.setAttribute("Permissions", SecurityService.getMenuList(httpSession.getAttribute("userName")+""));
				return "redirect:/loginSuccess";
			}
		}
}
